#include "include/PinPolygon.h"
#include <queue>
#include <unordered_set>


class PathNode {
public:
    Point position;
    PinPolygon* pin;  // 关联的PinPolygon
    PathNode* prev;   // 前驱节点
    PathNode* next;   // 后继节点

    PathNode(const Point& pos, PinPolygon* p = nullptr)
        : position(pos), pin(p), prev(nullptr), next(nullptr) {
    }
    // 在this节点后插入新节点
    void insertAfter(PathNode* newNode) {
        if (!newNode) return;

        newNode->prev = this;
        newNode->next = this->next;

        if (this->next) {
            this->next->prev = newNode;
        }
        this->next = newNode;
    }

    // 在this节点前插入新节点
    void insertBefore(PathNode* newNode) {
        if (!newNode) return;
        newNode->prev = this->prev;
        newNode->next = this;

        if (this->prev) {
            this->prev->next = newNode;
        }
        this->prev = newNode;
    }

    // 从链表中移除当前节点
    void removeFromList() {
        if (prev) prev->next = next;
        if (next) next->prev = prev;
        prev = nullptr;
        next = nullptr;
    }
    void deleteCurruntNode() {
        removeFromList();
        delete this;
    }
    void deleteRelatedNodes() {
        if (!this) return;

        // 断开环形连接
        if (prev) prev->next = nullptr;
        if (next) next->prev = nullptr;
        PathNode* prevChain = this->prev;
        PathNode* nextChain = this->next;
        delete this;

        // 安全删除前向链（防止环形）
        PathNode* currentPrev = prevChain;
        std::unordered_set<PathNode*> deletedNodes;
        while (currentPrev && deletedNodes.find(currentPrev) == deletedNodes.end()) {
            PathNode* temp = currentPrev->prev;
            deletedNodes.insert(currentPrev);
            delete currentPrev;
            currentPrev = temp;
        }

        // 安全删除后向链
        PathNode* currentNext = nextChain;
        while (currentNext && deletedNodes.find(currentNext) == deletedNodes.end()) {
            PathNode* temp = currentNext->next;
            deletedNodes.insert(currentNext);
            delete currentNext;
            currentNext = temp;
        }
    }
};
